import API from '@/main/common/api';
import { PluginHandler } from '@/core';
import path from 'path';
import fs from 'fs';
import getLocalDataFile from './getLocalDataFile';
import { PLUGIN_INSTALL_DIR as baseDir } from '@/common/constans/main';

const configPath = path.join(getLocalDataFile(), './rubick-local-plugin.json');

let registry;
let pluginInstance;
(async () => {
  try {
    const res = await API.dbGet({
      data: {
        id: 'rubick-localhost-config',
      },
    });
    registry = res && res.data.register;
    pluginInstance = new PluginHandler({
      baseDir,
      registry,
    });
  } catch (e) {
    pluginInstance = new PluginHandler({
      baseDir,
      registry,
    });
  }
})();

global.LOCAL_PLUGINS = {
  // 插件列表
  PLUGINS: [],
  // 下载插件
  async downloadPlugin(plugin) {
    console.log('downloadPlugin', plugin);
    console.log(pluginInstance);
  },

  /**
   * 获取本地插件
   * @returns
   */
  getLocalPlugins() {
    try {
      if (!global.LOCAL_PLUGINS.PLUGINS.length) {
        global.LOCAL_PLUGINS.PLUGINS = JSON.parse(
          fs.readFileSync(configPath, 'utf-8')
        );
      }
      return global.LOCAL_PLUGINS.PLUGINS;
    } catch (e) {
      global.LOCAL_PLUGINS.PLUGINS = [];
      return global.LOCAL_PLUGINS.PLUGINS;
    }
  },
  /**
   * 添加插件
   * @param plugin
   */
  addPlugin(plugin) {
    let has = false;
    const currentPlugins = global.LOCAL_PLUGINS.getLocalPlugins();
    currentPlugins.some((p) => {
      has = p.name === plugin.name;
      return has;
    });
    if (!has) {
      currentPlugins.unshift(plugin);
      global.LOCAL_PLUGINS.PLUGINS = currentPlugins;
      fs.writeFileSync(configPath, JSON.stringify(currentPlugins));
    }
  },
};
